﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using _5E.Utils.FileHelper;
using _5E.Utils.WebHelper;
using Newtonsoft.Json;
using Pool.WebSite.Service.Models;

namespace Pool.WebSite.Service.Adapter
{
    class AttachmentAdapter
    {
        public const string PATH = "attachment_path";
        public const string MAX_SIZE = "attachment_max_size";
        public const string TOO_BIG = "attachment_too_big";
        public const string EXNTESION = "attachment_extension";
        public const string REGEX_EXTENSION = "ext";
        public const string FILE_EXTENSION_REGEX_FORMAT = @"{0}:(?<" + REGEX_EXTENSION + @">[\w+\.?]+)\/";

        [Ajax]
        public string Upload(string dir, HttpPostedFile attachment)
        {
            if (null == attachment)
                return ToErrorMessage("请选择文件");

            Int32 maxSize = Convert.ToInt32(ConfigurationManager.AppSettings[MAX_SIZE]);
            if (maxSize < attachment.ContentLength)
                return ToErrorMessage(ConfigurationManager.AppSettings[TOO_BIG]);

            string savePath = HttpContext.Current.Server.MapPath(string.Format(ConfigurationManager.AppSettings[PATH], dir));
            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);

            Regex reg = new Regex(string.Format(FILE_EXTENSION_REGEX_FORMAT, dir));
            Group group = reg.Match(ConfigurationManager.AppSettings[EXNTESION]).Groups[REGEX_EXTENSION];
            if (null == group)
                return ToErrorMessage("不支持该类型文件!");
            string fileExtension = Path.GetExtension(attachment.FileName).ToLower();
            if (string.IsNullOrEmpty(fileExtension) || -1 == group.Value.IndexOf(fileExtension))
                return ToErrorMessage("只允许" + group.Value + "格式");

            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) +
                fileExtension;
            attachment.SaveAs(savePath + newFileName);
            return new StringBuilder("{\"error\":0,")
                .AppendFormat("\"url\":\"{0}{1}{2}\"", AjaxHelper.WebSiteUrl,
                    string.Format(ConfigurationManager.AppSettings[PATH], dir), newFileName)
                .Append("}").ToString();
        }

        [Ajax]
        public string GetAll(string dir, string order)
        {
            string[] fileNames = GetOrderFileNames(dir, order);
            string fileJSON = JsonConvert.SerializeObject(Array.ConvertAll(fileNames, nm => new AttachmentDto(new FileInfo(nm)).ToDto()));
            StringBuilder result = new StringBuilder("{")
                .Append("\"moveup_dir_path\":\"\",\"current_dir_path\":\"\"")
                .AppendFormat(",\"current_url\":\"{0}{1}\"", AjaxHelper.WebSiteUrl,
                    string.Format(ConfigurationManager.AppSettings[PATH], dir))
                .AppendFormat(",\"total_count\":{0}", fileNames.Length)
                .AppendFormat(",\"file_list\":{0}", fileJSON)
                .Append("}");
            return result.ToString();
        }

        private string[] GetOrderFileNames(string dir, string order)
        {
            string savePath = HttpContext.Current.Server.MapPath(string.Format(ConfigurationManager.AppSettings[PATH], dir));
            string[] fileNames = Directory.GetFiles(savePath);
            switch (order.ToLower())
            {
                case "size":
                    Array.Sort(fileNames, new SizeSorter());
                    break;
                case "type":
                    Array.Sort(fileNames, new TypeSorter());
                    break;
                case "name":
                default:
                    Array.Sort(fileNames, new NameSorter());
                    break;
            }
            return fileNames;
        }

        private string ToErrorMessage(string msg)
        {
            return new StringBuilder("{")
                .AppendFormat("\"error\":1,\"message\":\"{0}\"", msg)
                .Append("}").ToString();
        }
    }
}
